package com.qf.dao.impl;

import com.qf.dao.CartDao;
import com.qf.domain.Cart;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public void insert(Cart cart) {
        String sql = " insert into tb_cart (id,pid,num,money) values (?,?,?,?) ";
        Object[] params = {cart.getId(),cart.getPid(),cart.getNum(),cart.getMoney()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Cart select(Integer uid, int goodId) {
        String sql = " select * from tb_cart where id=? and pid=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Cart.class),uid,goodId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Cart cart) {
        String sql = " update tb_cart set num=?,money=? where id=? and pid=? ";
        Object[] params = {cart.getNum(),cart.getMoney(),cart.getId(),cart.getPid()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Cart> select(Integer uid) {
        String sql = " select * from tb_cart where id=? ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Cart.class),uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Integer uid, int goods_id) {
        String sql = " delete from tb_cart where id=? and pid=? ";
        try {
            queryRunner.update(sql, uid, goods_id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAll(Integer uid) {
        //生成订单后修改
        QueryRunner queryRunner1 = new QueryRunner();
        Connection connection = DataSourceUtil.getConnection();
        String sql = " delete from tb_cart where id=? ";
        try {
            queryRunner.update(connection,sql, uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DataSourceUtil.closeAll(null,null,connection );
        }
    }

}
